package com.kye.express.business.president_online;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.business.login.LoginActivity;
import com.kye.express.databinding.FragmentPresidentonlineListBinding;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.president_online.PresidentOnlineListBean;
import com.kye.model.bean.user.User;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 总裁热线留言列表
 */
public class PresidentOnlineListFragment extends BaseAppCompatFragment implements PresidentOnlineListFragmentContract.PresidentOnlineListView {
    private FragmentPresidentonlineListBinding mBinding;

    protected MultiTypeAdapter mAdapter;
    protected Items mDatas = new Items();

    private PresidentOnlineListener mListener = null;

    protected PresidentOnlineListFragmentContract.PresidentOnlineListViewPresenter mPresenter;
    private Dialog mLoadingDialog;

    public static PresidentOnlineListFragment newInstance() {
        PresidentOnlineListFragment fragment = new PresidentOnlineListFragment();
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mListener = (context instanceof PresidentOnlineListener) ? (PresidentOnlineListener) context : null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_presidentonline_list, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mBinding = FragmentPresidentonlineListBinding.bind(view);
        mPresenter = new PresidentOnlineListFragmentContract.PresidentOnlineListViewPresenter(getActivity());
        mPresenter.bind(this);
        getActivity().setTitle(getString(R.string.president_online));
        initView();
        initEvent();
        mPresenter.onUser();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPresenter.unbind();
    }

    private void initView() {
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(PresidentOnlineListBean.DatasBean.class, new PresidentOnlineListItemViewBinder(getActivity(),mListener));
        mBinding.recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        mBinding.recyclerview.setHasFixedSize(true);
        mBinding.recyclerview.setNestedScrollingEnabled(false);
        RecyclerViewDivider.with(getActivity())
                .color(getResources().getColor(R.color.grey))
                .size(ScreenUtils.dp2px(getActivity(), 1))
                .hideLastDivider()
                .build()
                .addTo(mBinding.recyclerview);
        mBinding.recyclerview.setItemAnimator(new DefaultItemAnimator());
        mAdapter.setItems(mDatas);
        mBinding.recyclerview.setAdapter(mAdapter);
        mBinding.refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPresenter.loadDatas(false, false);
            }

            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                mPresenter.loadDatas(false, true);
            }

        });
    }

    private void initEvent() {
        RxView.clicks(mBinding.btnAddMessage)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (mListener != null) {
                            mListener.onAddMessage();
                        }
                    }
                });
    }

    @Override
    public void onComplete(boolean isLoadMore) {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        if (isLoadMore) {
            mBinding.refreshLayout.finishLoadmore();
        } else {
            mBinding.refreshLayout.finishRefresh();
        }
    }

    @Override
    public void onLoading() {
        try{
            if (mLoadingDialog == null) {
                mLoadingDialog = new KyeProgressDialog.Builder(getActivity())
                        .build();
            }
            mLoadingDialog.show();
        }catch (Exception e){

        }
    }

    @Override
    public void onLoaded(PresidentOnlineListBean resultDatas, boolean isLoadMore) {
        if (resultDatas != null && resultDatas.getDatas() != null) {
            if (!isLoadMore) {
                mDatas.clear();
                mDatas.addAll(resultDatas.getDatas());
                mAdapter.notifyDataSetChanged();
            } else {
                List<PresidentOnlineListBean.DatasBean> datas = (List<PresidentOnlineListBean.DatasBean>) mAdapter.getItems();
                if (datas != null) {
                    int start = datas.size();
                    datas.addAll(resultDatas.getDatas());
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
        if (mAdapter.getItems().size() <= 0) {
            mBinding.statusLayout.showEmptyView();
        } else {
            mBinding.statusLayout.showContentView();
        }
    }

    @Override
    public void onError(String msg, boolean isLoadMore) {
        ToastManager.show(getActivity(), msg, Toast.LENGTH_SHORT);
        if (isLoadMore) {
            mBinding.refreshLayout.finishLoadmore(false);
        } else {
            mBinding.refreshLayout.finishRefresh(false);
        }
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onUser(User user) {
        if (user != null && !TextUtils.isEmpty(user.getToken())) {
            mPresenter.loadDatas(true, false);
        } else {
            LoginActivity.startActivity(getActivity());
        }
    }
}
